package com.ovopark.firecar.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log

/**
 * 服务工具类
 * Created by dyx on 2016/10/26.
 */
object ServiceUtils {
    private const val TAG = "ServiceUtils"

    @JvmStatic
    fun startService(context: Context, intent: Intent?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
    }

    @JvmOverloads
    @JvmStatic
    fun startService(mContext: Context, serviceName: Class<*>?, bundle: Bundle? = null) {
        val intent = Intent(mContext, serviceName)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
//        mContext.startService(intent)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mContext.startForegroundService(intent)
        } else {
            mContext.startService(intent)
        }
    }

    @JvmStatic
    fun stopWorkingService(mContext: Context, serviceClass: Class<*>) {
        val isShopRunning = isServiceWorking(mContext, serviceClass)
        if (isShopRunning) {
            Log.d(TAG, "stop serviceName = " + serviceClass.name)
            mContext.stopService(Intent(mContext, serviceClass))
        }
    }

    @JvmStatic
    fun isServiceWorking(mContext: Context, serviceClass: Class<*>): Boolean {
        return isServiceWork(mContext, serviceClass.name)
    }

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    fun isServiceWork(mContext: Context, serviceName: String): Boolean {
        var isWork = false
        val myAM = mContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val myList = myAM.getRunningServices(100)
        if (myList.size <= 0) {
            return false
        }
        val size = myList.size
        for (i in 0 until size) {
            val mName = myList[i].service.className
            if (mName == serviceName) {
                isWork = true
                break
            }
        }
        return isWork
    }
}